package com.javachmapi.img;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImageMerge {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageMerge.class);


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ImageMerge tt = new ImageMerge();

//		BufferedImage d = tt.loadImageLocal("d:\\1.jpg");
//		BufferedImage t = tt.loadImageLocal("d:\\2.png");
//		d = tt.modifyImagetogeter(t, d, 530, 1050);
//		String s = "爱订不订爱订不订爱订不订爱订不订";
//		if (s.length() > 10) {
//			String[] ss = new String[] { s.substring(0, 10), s.substring(10) };
//			tt.writeImageLocal("d:\\3.jpg", tt.modifyImage(d, ss, 40, 1120, false));
//		} else {
//			tt.writeImageLocal("d:\\3.jpg", tt.modifyImage(d, s, 40, 1150));
//		}
		// tt.writeImageLocal("D:\\cc.jpg", tt.modifyImagetogeter(b, d));
		// 将多张图片合在一起
		//ADManager.createUsjQRcode("349504604579","998487659366005",120);
		logger.info("success");

	}

	private Font font = new Font("Microsoft YaHei", Font.BOLD, 40);// 添加字体的属性设置
	private Font font2 = new Font("Microsoft YaHei", Font.BOLD, 9);// 添加字体的属性设置
	private Graphics2D g = null;

	private int fontsize = 30;

	private int x = 0;

	private int y = 0;

	/**
	 * 导入本地图片到缓冲区
	 */
	public BufferedImage loadImageLocal(String imgName) {
		try {
			return ImageIO.read(new File(imgName));
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
		return null;
	}

	/**
	 * 导入网络图片到缓冲区
	 */
	public BufferedImage loadImageUrl(String imgName) {
		try {
			URL url = new URL(imgName);
			return ImageIO.read(url);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 生成新图片到本地
	 */
	public void writeImageLocal(String newImage, BufferedImage img) {
		if (newImage != null && img != null) {
			try {
				File outputfile = new File(newImage);
				ImageIO.write(img, "jpg", outputfile);
			} catch (IOException e) {
                logger.error("文件【" + newImage + "】读取错误：" + e.getMessage(), e);
			}
		}
	}
	public BufferedImage modifyUsjImagetogeter(BufferedImage b, BufferedImage d, int x, int y) {

		try {
			int w = b.getWidth();
			int h = b.getHeight();
			g = d.createGraphics();
			//g.setBackground(Color.RED);
			g.setColor(Color.RED);
			g.drawImage(b, x, y, w, h,null);
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return d;
	}
	public BufferedImage modifyUsjImage(BufferedImage img, Object content, int x, int y) {
		try {
			int w = img.getWidth();
			int h = img.getHeight();
			g = img.createGraphics();
			//g.setBackground(Color.red);
			g.setColor(Color.red);// 设置字体颜色

			if (this.font2 != null)
				g.setFont(this.font2);
			// 验证输出位置的纵坐标和横坐标
			if (x >= w || y >= h) {
				this.x = h - this.fontsize + 2;
				this.y = w;
			} else {
				this.x = x;
				this.y = y;
			}
			if (content != null) {
				g.drawString(new String(content.toString().getBytes(), "UTF-8"), this.x, this.y);
			}
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}

		return img;
	}

	public BufferedImage createUsjImage(int x, int y,String ss) {
		try {
			BufferedImage bi = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
			g = bi.createGraphics();
//			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//			g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
//			g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
//			g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
			g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g.setComposite(AlphaComposite.Src);
			g.fillRect(0, 0, x, y);
			g.setBackground(Color.white);
			g.setFont(new Font("Microsoft YaHei", Font.BOLD, 9));
			g.setColor(Color.RED);// 设置字体颜色
			if(StringUtils.isNotBlank(ss)) {
				g.drawString(new String(ss.getBytes(), "UTF-8"), 5, 8);
			}
			g.getDeviceConfiguration().createCompatibleImage(x, y, Transparency.TRANSLUCENT);
			g.dispose();
			return bi;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return null;
	}
	public BufferedImage createUsjImage(int x, int y) {
		try {
			BufferedImage bi = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_BINARY);
			g = bi.createGraphics();
			g.setBackground(Color.white);
			g.fillRect(0, 0, x, y);
			g.setColor(Color.black);
			g.getDeviceConfiguration().createCompatibleImage(x, y, Transparency.TRANSLUCENT);
			g.dispose();
			return bi;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 生成新图片
	 */
	public void writeUsjImageLocal(BufferedImage img) {
		if (img != null) {
			try {
				ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
				ImageIO.write(img, "jpg", outputStream);
			} catch (IOException e) {
				logger.error("文件【" + img + "】读取错误：" + e.getMessage(), e);
			}
		}
	}
	/**
	 * 设定文字的字体等
	 */
	public void setFont(String fontStyle, int fontSize) {
		this.fontsize = fontSize;
		this.font = new Font(fontStyle, Font.BOLD, fontSize);
	}

	public void setFont(Font font) {
		this.font = font;
	}

	/**
	 * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
	 */
	public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y) {

		try {
			int w = img.getWidth();
			int h = img.getHeight();
			g = img.createGraphics();
			g.setBackground(Color.WHITE);
			g.setColor(Color.BLACK);// 设置字体颜色
			if (this.font != null)
				g.setFont(this.font);
			// 验证输出位置的纵坐标和横坐标
			if (x >= w || y >= h) {
				this.x = h - this.fontsize + 2;
				this.y = w;
			} else {
				this.x = x;
				this.y = y;
			}
			if (content != null) {
				g.drawString(new String(content.toString().getBytes(), "UTF-8"), this.x, this.y);
			}
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return img;
	}

	/**
	 * 文字内部不需要做转码处理
	 * 
	 * @param img
	 * @param content
	 * @param x
	 * @param y
	 * @return
	 */
	public BufferedImage modifyImage1(BufferedImage img, String content, int x, int y) {

		try {
			int w = img.getWidth();
			int h = img.getHeight();
			g = img.createGraphics();
			g.setBackground(Color.WHITE);
			g.setColor(Color.BLACK);// 设置字体颜色
			if (this.font != null)
				g.setFont(this.font);
			// 验证输出位置的纵坐标和横坐标
			if (x >= w || y >= h) {
				this.x = h - this.fontsize + 2;
				this.y = w;
			} else {
				this.x = x;
				this.y = y;
			}
			if (content != null) {
				g.drawString(content, this.x, this.y);
			}
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return img;
	}

	/**
	 * 修改图片,返回修改后的图片缓冲区（输出多个文本段） xory：true表示将内容在一行中输出；false表示将内容多行输出
	 */
	public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y, boolean xory) {
		try {
			int w = img.getWidth();
			int h = img.getHeight();
			g = img.createGraphics();
			g.setBackground(Color.WHITE);
			g.setColor(Color.BLACK);
			if (this.font != null)
				g.setFont(this.font);
			// 验证输出位置的纵坐标和横坐标
			if (x >= w || y >= h) {
				this.x = h - this.fontsize + 2;
				this.y = w;
			} else {
				this.x = x;
				this.y = y;
			}
			if (contentArr != null) {
				int arrlen = contentArr.length;
				if (xory) {
					for (int i = 0; i < arrlen; i++) {
						g.drawString(contentArr[i].toString(), this.x, this.y);
						this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置
					}
				} else {
					for (int i = 0; i < arrlen; i++) {
						g.drawString(contentArr[i].toString(), this.x, this.y);
						this.y += this.fontsize + 8;// 重新计算文本输出位置
					}
				}
			}
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return img;
	}

	/**
	 * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
	 * 
	 * 时间:2007-10-8
	 * 
	 * @param img
	 * @return
	 */
	public BufferedImage modifyImageYe(BufferedImage img) {

		try {
			int w = img.getWidth();
			int h = img.getHeight();
			g = img.createGraphics();
			g.setBackground(Color.WHITE);
			g.setColor(Color.blue);// 设置字体颜色
			if (this.font != null)
				g.setFont(this.font);
			g.drawString("reyo.cn", w - 85, h - 5);
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return img;
	}

	public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d, int x, int y) {

		try {
			int w = b.getWidth();
			int h = b.getHeight();

			g = d.createGraphics();
			g.drawImage(b, x, y, w, h, null);
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return d;
	}

	/**
	 * 
	 * @param b
	 * @param d
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @return
	 */
	public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d, int x, int y, int w, int h) {

		try {
			g = d.createGraphics();
			g.drawImage(b, x, y, w, h, null);
			g.dispose();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return d;
	}

	/**
	 * 图片设置圆角
	 * 
	 * @param srcImage
	 * @param radius
	 * @param border
	 * @param padding
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding)
			throws IOException {
		int width = srcImage.getWidth();
		int height = srcImage.getHeight();
		int canvasWidth = width + padding * 2;
		int canvasHeight = height + padding * 2;

		BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
		Graphics2D gs = image.createGraphics();
		gs.setComposite(AlphaComposite.Src);
		gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		gs.setColor(Color.WHITE);
		gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
		gs.setComposite(AlphaComposite.SrcAtop);
		gs.drawImage(setClip(srcImage, radius), padding, padding, null);
		if (border != 0) {
			gs.setColor(Color.GRAY);
			gs.setStroke(new BasicStroke(border));
			gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
		}
		gs.dispose();
		return image;
	}

	/**
	 * 图片设置圆角
	 * 
	 * @param srcImage
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage setRadius(BufferedImage srcImage) throws IOException {
		int radius = (srcImage.getWidth() + srcImage.getHeight()) / 6;
		return setRadius(srcImage, radius, 2, 1);
	}

	/**
	 * 图片切圆角
	 * 
	 * @param srcImage
	 * @param radius
	 * @return
	 */
	public static BufferedImage setClip(BufferedImage srcImage, int radius) {
		int width = srcImage.getWidth();
		int height = srcImage.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D gs = image.createGraphics();

		gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
		gs.drawImage(srcImage, 0, 0, null);
		gs.dispose();
		return image;
	}

	/**
	 * 传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的
	 * @param bi1
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage convertCircular(BufferedImage bi1) throws IOException {
		// 透明底的图片
		BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
		Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
		Graphics2D g2 = bi2.createGraphics();
		g2.setClip(shape);
		// 使用 setRenderingHint 设置抗锯齿
		g2.drawImage(bi1, 0, 0, null);
		// 设置颜色
		g2.setBackground(Color.WHITE);
		g2.dispose();
		return bi2;
	}

	/**
	 * 缩小Image，此方法返回源图像按给定宽度、高度限制下缩放后的图像
	 *
	 * @param inputImage
	 * @param newWidth
	 *            ：压缩后宽度
	 * @param newHeight
	 *            ：压缩后高度
	 * @throws IOException
	 *             return
	 */
	public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
		// 获取原始图像透明度类型
		int type = inputImage.getColorModel().getTransparency();
		int width = inputImage.getWidth();
		int height = inputImage.getHeight();
		// 开启抗锯齿
		RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		// 使用高质量压缩
		renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		BufferedImage img = new BufferedImage(newWidth, newHeight, type);
		Graphics2D graphics2d = img.createGraphics();
		graphics2d.setRenderingHints(renderingHints);
		graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
		graphics2d.dispose();
		return img;
	}
}
